package org.andao.commons.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import org.andao.commons.cache.CacheAppManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * seewo open api 抽象类.
 * @author Seewo Software - Marco.hu(huzhiguo@cvte.cn)
 *
 */
public abstract class AbstractOpenApi {

	protected static Logger logger = LoggerFactory.getLogger(AbstractOpenApi.class);
	
	protected Map<String,Object> result = new ConcurrentHashMap<String,Object>();//返回结果map
	
    protected static final String STATUS_CODE = "statusCode";
    
    protected static final String MSG_ERROR = "errorMassage";
    
    protected  enum StatusCode{
    	
    	SUCCESS(200),REPEAT_SUBMIT(400),AUTHOR_ERROR(401),
    	USER_INVALID(402),PASSWORD_INVALID(403),
    	NOT_FOUND(404),EMPTY_PARA(405),SYSTEM_ERROR(500);
    	
    	private int code;
    	
    	private StatusCode(int code){
    		this.code = code;
    	}
    	

		public int getCode() {
			return code;
		}


		@Override
		public String toString() {			
			return String.valueOf(code);
		}   	
    	
    }
   
	/**
	 * 获取客户端的输出流.
	 * @param in
	 * @return
	 * @throws IOException
	 */
	protected  String getRequestBody(InputStream in) throws IOException {
	    String body = null;
	    StringBuilder stringBuilder = new StringBuilder();
	    BufferedReader bufferedReader = null;
	
	    try {
	         if (in != null) {	        	
	            //bufferedReader = new BufferedReader(new InputStreamReader(in));
	        	 bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));//fixed:windows下会乱码
	            char[] charBuffer = new char[128];
	            int bytesRead = -1;
	            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
	                stringBuilder.append(charBuffer, 0, bytesRead);
	            }
	        } else {
	            stringBuilder.append("");
	        }
	    } catch (IOException ex) {
	        throw ex;
	    } finally {
	        if(null != in){
	            in.close();
	        }
	        if (null != bufferedReader) {
	            bufferedReader.close();
	        }
	    }
	
	    body = stringBuilder.toString();
	    return body;
	}
	
	protected String getRootUrl(HttpServletRequest request){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() + request.getContextPath();
	}

	protected String getRealUrl(HttpServletRequest request){
	    return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
	}
	
	protected String getDownloadUrl(HttpServletRequest request){
		return getRealUrl(request) + CacheAppManager.getSysConfigurationByCode("web.uploadfile.rooturl").getParamValue();
	}
	
	/**
	 * 校验客户端请求的参数
	 * @param Map<String, String> -- map, key: 参数名称, value: 参数值
	 * @return Map<String, String> -- 错误参数表
	 */
	protected Map<String, String> validPara(Map<String, String> paraMap){
	    Map<String, String> wrongParaMap = new HashMap<String, String>();
	    Iterator<Entry<String, String>> paraIterator = paraMap.entrySet().iterator();
	    while(paraIterator.hasNext()){
	        Entry<String, String> paraEntry = paraIterator.next();
	        if(StringUtils.isBlank(paraEntry.getValue())){
	            wrongParaMap.put(paraEntry.getKey(), paraEntry.getKey() + " is empty");
	        }
	    }
	    return wrongParaMap;
	}
	
	/**
	 * 校验是否通过请求签名认证.
	 * @param request
	 * @return
	 */
	protected boolean hasAuthenticated(HttpServletRequest request){
		//return null != request.getAttribute(HmacAttributes.X_AUTHENTICATED_USERNAME); //TODO 2.0需要加入
		return true;
	}
	
	/**
	 * 获取服务器文件存储的根目录.
	 * @return
	 */
	protected File getServerRootPath(){
		File parentFolder = new File(FileUriContext.instance().getServerStoreRootPath());
		 if(!parentFolder.exists()){
			 logger.warn("web.uploadfile.rootpath目录不存在!");				
		 }
		return parentFolder;
	}
	
}
